<?php
/**
 * phpmailer 邮件
 */
namespace app\libs\mail;

class Mail {
    private $lang = 'zh_cn';
    private $msg = '';
    private $options = array(
        'host' => 'smtp.126.com',
        'port' => '25',
        'username' => 'xxx@126.com',  // 发邮件的邮箱用户名
        'password' => 'xxxxxx',  // 邮箱密码
        'sender_email' => 'xxx@126.com',  // 显示用 给收件人看
        'sender_name' => 'title'  // 显示用 给收件人看
    );

    public function __construct(& $config = null) {
        include __DIR__ . '/phpmailer/PHPMailerAutoload.php';

        if(null !== $config) {
            $this->options = $config;
        }
    }

    /**
     * 发送 smtp 邮件
     * @param toEmail 收件人
     * @param subject 主题
     * @param
     */
    public function sendMail($toEmail, $subject, & $body) {
        $mail = new \PHPMailer();
        $mail->setLanguage($this->lang);
        $mail->CharSet = "UTF-8";
        $mail->Encoding	= "base64";

        $mail->isSMTP();  // Set mailer to use SMTP
        $mail->Host = $this->options['host'];  // Specify main and backup SMTP servers
        $mail->Port	= $this->options['port'];
        $mail->SMTPAuth = true;  // Enable SMTP authentication
        $mail->Username = $this->options['username'];  // SMTP username
        $mail->Password = $this->options['password'];  // SMTP password
        //$mail->SMTPSecure = 'ssl';  // Enable encryption, 'ssl' 'tls' also accepted
        $mail->Sender = $this->options['username'];  // 真正的发送者

        // 发送者显示信息
        $mail->From = $this->options['sender_email'];
        $mail->FromName = $this->options['sender_name'];

        // 接收者
        if(is_array($toEmail)) {
            foreach($toEmail as $v){
                $mail->AddAddress($v);
            }
        } else {
            $mail->addAddress($toEmail);
        }

        //$mail->addReplyTo('info@example.com', 'Information');
        //$mail->addCC('cc@example.com');
        //$mail->addBCC('bcc@example.com');

        $mail->isHTML(true);  // Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AltBody = 'text/html';

        $result = $mail->send();

        $this->msg = $mail->ErrorInfo;

        return $result;
    }

    public function getMsg() {
        return $this->msg;
    }
}
